﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Dapper;
using WebMvc.Models;

namespace WebMvc.Dao
{
    public abstract class BaseDao<T> where T : BaseModel
    {
        protected BaseDao(IDbConnection conn)
        {
            if (conn == null)
                throw new ArgumentNullException("conn");

            Connection = conn;
        }

        protected IDbConnection Connection { get; private set; }

        // Propiedades que cada Dao tiene que implementar
        protected abstract string SelectCmd { get; }
        protected abstract string DeleteCmd { get; }

        public IEnumerable<T> GetAll()
        {
            return Connection.Query<T>(SelectCmd, new { });
        }

        public T GetById(int id)
        {
            var cmd = SelectCmd + " WHERE Id = @id";
            var result = Connection.Query<T>(cmd, new { @id = id });

            return result.Any() ? result.First() : null;
        }

        public T GetByNombre(string nombre)
        {
            var cmd = SelectCmd + " WHERE Nombre = @nombre";
            var result = Connection.Query<T>(cmd, new { @nombre = nombre });

            return result.Any() ? result.First() : null;
        }

        public void Delete(int id)
        {
            var cmd = DeleteCmd + " WHERE Id = @id";
            Connection.Execute(cmd, new {@id = id} );
        }
    }
}